"""
@Author：WangYuXiang
@E-mile：Hill@3io.cc
@CreateTime：2021/3/24 16:35
@DependencyLibrary：无
@MainFunction：无
@FileDoc： 
    qr.py
    文件说明
@ChangeHistory:
    datetime action why
    example:
    2021/3/24 16:35 change 'Fix bug'
        
"""

from common.auth.models import UserModel, RoleModel, PermissionModel, GroupModel
from sanic_rest_framework.exceptions import ValidationException
from sanic_rest_framework.fields import CharField, IntegerField
from sanic_rest_framework.serializers import ModelSerializer, Serializer


class AdminSiteLoginSerializer(ModelSerializer):
    """后台管理界面登录"""

    class Meta:
        model = UserModel
        exclude = ('login_datetime', 'last_login_datetime', 'is_active', 'is_super_admin')
        write_only_fields = ('account', 'pwd')
        read_only_fields = ('nickname', 'phone', 'qq', 'wx', 'tel', 'birthday')


class RoleReadSerializer(ModelSerializer):
    class Meta:
        model = RoleModel
        fields = ('id', 'name', 'code')
        read_only_fields = ('id', 'name', 'code')


class AdminSiteLoginByAPSerializer(ModelSerializer):
    roles = RoleReadSerializer(many=True, source='roles', read_only=True)

    class Meta:
        model = UserModel
        fields = ('account', 'pwd', 'roles')
        write_only_fields = ('account', 'pwd')
        read_only_fields = ('roles',)


class AdminSiteLoginByTRSerializer(Serializer):
    """token 及 role_id 序列化器"""
    role_id = CharField(write_only=True, required=True)


class UserModelSerializer(ModelSerializer):
    """用户管理"""

    class Meta:
        model = UserModel
        exclude = ('pwd', 'create_time', 'update_time',)
        read_only_fields = ('last_login_datetime', 'login_datetime', 'id',)

    password = CharField(write_only=True)

    def validate(self, attrs):
        password = attrs.pop('password', None)
        if password:
            attrs['pwd'] = UserModel.encryption_password(password)
        return attrs


class UserSearchSerializer(Serializer):
    """用户搜索"""
    account = CharField(source='account',read_only=True)
    value = CharField(source='nickname', read_only=True)
    key = CharField(source='id', read_only=True)
    
         
class PermissionModelSerializer(ModelSerializer):
    """权限模型系列化器"""

    class Meta:
        model = PermissionModel
        exclude = ('create_time', 'update_time',)


class GroupModelSerializer(ModelSerializer):
    """组织机构模型系列化器"""
    parent = CharField(required=False, allow_null=True, write_only=True)

    class Meta:
        model = GroupModel
        exclude = ('create_time', 'update_time')
        read_only_fields = ('id',)

    async def validate(self, attrs):

        parent_id = attrs.pop('parent')
        if self.is_partial() and parent_id is None:
            attrs['parent'] = parent_id
        if parent_id:
            group = await GroupModel.get_or_none(id=parent_id)
            if not group:
                raise ValidationException({'parent': '父级组织不存在'})
            attrs['parent'] = group
        return attrs


class RoleModelSerializer(ModelSerializer):
    """角色岗位模型系列化器"""

    parent = CharField(required=False, allow_null=True, write_only=True)

    class Meta:
        model = RoleModel
        exclude = ('create_time', 'update_time')
        read_only_fields = ('id',)

    async def validate(self, attrs):
        parent_id = attrs.pop('parent')
        group = await GroupModel.get_or_none(id=parent_id)
        if not group:
            raise ValidationException({'parent': '父级组织不存在'})
        attrs['group'] = group
        return attrs


class PermissionCodeSerializer(Serializer):
    code = CharField()


class DeletePermissionCodeSerializer(PermissionCodeSerializer):
    pass


class AddPermissionCodeSerializer(PermissionCodeSerializer):
    pass


class PermissionHandleGetSerializer(Serializer):
    model_type = CharField(required=True)
    pk = CharField(required=True)

    def validate_model_type(self, value):
        if value in ('role', 'group'):
            return value
        raise ValidationException('错误的数据%s' % value)


class PermissionHandlePostSerializer(PermissionHandleGetSerializer):
    add_perm = AddPermissionCodeSerializer(many=True, write_only=True, allow_null=True)
    delete_perm = DeletePermissionCodeSerializer(many=True, write_only=True, allow_null=True)

    async def validate(self, attrs):
        add_perms = attrs.pop('add_perm', [])
        delete_perms = attrs.pop('delete_perm', [])
        add_perm_objs = []
        delete_perm_objs = []
        for i in add_perms:
            perm = await PermissionModel.get(pk=i['code'])
            if perm:
                add_perm_objs.append(perm)
        for i in delete_perms:
            perm = await PermissionModel.get(pk=i['code'])
            if perm:
                delete_perm_objs.append(perm)
        attrs.update({
            'add_perm': add_perm_objs,
            'delete_perm': delete_perm_objs
        })
        return attrs


class RoleEmployUserListSerializer(ModelSerializer):
    """角色下聘任的用户序列化器"""

    class Meta:
        model = UserModel
        fields = ('nickname', 'account', 'phone', 'is_active', 'is_super_admin')


class RoleDimsissSerializer(Serializer):
    """角色解聘序列化器"""
    account = CharField(required=True)
    pk = IntegerField(required=True)


class RoleEmployUserSerializer(Serializer):
    user_id = CharField(required=True)
    role_id = CharField(required=True)
